import { BufferAttribute, BufferGeometry, Mesh, MeshStandardMaterial, Object3D, Vector3} from "three";
import { pictrueTexture } from "./tTextures";

export const codeModels: Object3D[] = []

interface Vertices{
    positions: Array<number>[]
    cells: Array<number>[]
    normals: Array<number>[]
    uv: Array<number>[]
}
let vertices: Vertices = {
    positions: [],
    cells: [],
    normals: [],
    uv: []
}
// 创建顶点数组
const size: number = 10
const points: Array<number>[] = [
    [-size,size,size], // 顶面 第1个顶点
    [size,size,size], // 顶面 第2个顶点
    [size,size,-size], // 顶面 第3个顶点
    [-size,size,-size], // 顶面 第4个顶点
    [-size,-size,size], // 底面 第1个顶点
    [size,-size,size], // 底面 第2个顶点
    [size,-size,-size], // 底面 第3个顶点
    [-size,-size,-size], // 底面 第4个顶点
]
// 生成顶点信息
let cellIdx = 0
function quad(a:number, b:number, c:number, d:number){
    let A2B = new Vector3(...points[b]).sub(new Vector3(...points[a]));
    let A2C = new Vector3(...points[c]).sub(new Vector3(...points[a]));
    let norm = A2B.cross(A2C).normalize();
    let normalize = [norm.x, norm.y, norm.z];
    vertices.normals.push(normalize, normalize, normalize, normalize);
    [a,b,c,d].forEach(v=>{
        vertices.positions.push(points[v])
    });
    vertices.uv.push(
        [0,0],
        [1,0],
        [1,1],
        [0,1]
    )
    vertices.cells.push(
        [0,1,2].map(v=>v + cellIdx),
        [0,2,3].map(v=>v + cellIdx)
    )
    cellIdx += 4
}
// 每个面都生成顶点
quad(0,1,2,3)//上
quad(4,5,6,7)//下
quad(0,4,5,1)//前
quad(3,2,6,7)//后
quad(0,3,7,4)//左
quad(1,5,6,2)//右

// 创建缓冲几何体
const geometry: BufferGeometry =  new BufferGeometry()
// 设置顶点信息
let vertex: Float32Array = new Float32Array(vertices.positions.flat())
geometry.setAttribute("position", new BufferAttribute( vertex, 3 ))

// 设置顶点索引
const indexes: number[] = vertices.cells.flat()
geometry.setIndex(indexes)

// 设置法线，用于光照计算
let normals: Float32Array = new Float32Array(vertices.normals.flat())
geometry.setAttribute("normal", new BufferAttribute( normals, 3 ))

// 设置顶点UV坐标，设置法线辅助
let uv: Float32Array = new Float32Array(vertices.uv.flat())
geometry.setAttribute("uv", new BufferAttribute( uv, 2 ))

// 设置材质
const meterial: MeshStandardMaterial = new MeshStandardMaterial({
    color:0xffffff,
    metalness: 0.5,
    roughness: 0,
    map:pictrueTexture
})
const codeBox: Mesh = new Mesh(
    geometry,
    meterial
)
codeBox.position.y = 10
codeBox.position.x = 15
codeBox.position.z = 40
// 产生阴影
codeBox.castShadow = true;

codeModels.push()
